package com.lancoo.ccas52.util;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.StrUtil;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


/**
 * 根据字符串 处理返回所需数据
 */
public class WeekUtil {

    /**
     * 根据二进制字符串返回前端易读字符串
     *
     * @param week
     * @return
     */
    public static String binaryToString(String week) {
        ArrayList<Integer> list = new ArrayList<>();
        for (int i = 0; i < week.length(); i++) {
            if (week.charAt(i) == '1') {
                list.add(i + 1);
            }
        }
        StringBuilder stringBuilder = new StringBuilder();
        if (CollUtil.isEmpty(list)) {
            return stringBuilder.toString();
        }
        if (list.size() == 1) {
            return list.get(0).toString();
        }
        boolean flag = true;
        for (int i = 0; i < list.size() - 1; i++) {
            int before = list.get(i);
            int after = list.get(i + 1);
            if (after - before != 1) {
                //非连续
                flag = false;
                break;
            }
        }
        if (flag) {
            stringBuilder.append(list.get(0)).append("-").append(list.get(list.size() - 1));
            return stringBuilder.toString();
        } else {
            String join = StrUtil.join(",", list);
            return join;
        }
    }


    /**
     * 获取开课学期
     *
     * @param term  当前学期  2022-202301
     * @param grade 年级  2020级
     * @return
     */
    public static int getOpeningTerm(String term, String grade) {
        //学期年份
        String termYear = term.substring(0, 4);
        //第几学期
        String termWhich = term.substring(term.length() - 1);

        //该年级第一学期年份
        String gradeYear = grade.substring(0, 4);

        int year = Integer.parseInt(termYear) - Integer.parseInt(gradeYear);
        if (year < 0) {
            return 0;
        } else {
            return year * 2 + Integer.parseInt(termWhich);
        }
    }

    /**
     * 获取学期名称
     * 2023-202401 -> 2023上，   2023-202402 -> 2023下
     *
     * @param term
     * @return
     */
    public static String getTermName(String term) {
        //学期年份
        String termYear = term.substring(0, 4);
        //第几学期
        String termWhich = term.substring(term.length() - 1);
        return termYear + (termWhich.equals("1") ? "上" : "下");
    }

}
